package i2.application.fmw.struts.interceptors;

import i2.application.fmw.exceptions.ValidationException;
import i2.application.fmw.exceptions.ValidationMessage;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * Intercepteur pour les erreurs de validation.
 */
public class ValidationExceptionInterceptor extends AbstractInterceptor {

	/**
	 * le loggueur.
	 */
	private static final Logger logger = LoggerFactory.getLogger(ValidationExceptionInterceptor.class);
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Interception.
	 * 
	 * @see AbstractInterceptor#intercept(ActionInvocation)
	 * 
	 * @param invocation l'invocation
	 * @throws Exception en cas d'échec de l'action
	 * @return résultat de l'invocation
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		String result;

		try {
			result = invocation.invoke();

		} catch (final ValidationException e) {
			logger.warn("Erreur de validation");
			final Object action = invocation.getAction();
			if (action instanceof ActionSupport) {
				final ActionSupport actionSupport = (ActionSupport) action;
				for (ValidationMessage vm : e.getValidationMessages()) {
					actionSupport.addFieldError(vm.getKey(),actionSupport.getText(vm.getMessage()));
				}
			}
			return "input";
		}

		return result;
	}

}
